package com.aegis.common.mybatis.model;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @Author renogo
 *
 * @Version 1.0
 * @Descritube
 */
public class PageResult<T> {
    private List<T> records = Collections.emptyList();

    /**
     * 总数
     */
    private long total = 0;
    /**
     * 每页显示条数，默认 10
     */
    private long size = 10;

    /**
     * 当前页
     */
    private long current = 1;

    /**
     * 总页数
     */
    private long pages;

    public List<T> getRecords() {
        return records;
    }

    public PageResult<T> setRecords(List<T> records) {
        this.records = records;
        return this;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public long getCurrent() {
        return current;
    }

    public void setCurrent(long current) {
        this.current = current;
    }

    public long getPages() {
        return pages;
    }

    public void setPages(long pages) {
        this.pages = pages;
    }

    public <R> PageResult<R> convert(Function<? super T, ? extends R> mapper) {
        List<R> collect = this.getRecords().stream().map(mapper).collect(toList());
        return ((PageResult<R>) this).setRecords(collect);
    }


    public static <V> PageResult<V> exchange(IPage<V> page) {
        PageResult<V> pageVO = new PageResult<>();
        pageVO.setPages(page.getPages());
        pageVO.setCurrent(page.getCurrent());
        pageVO.setSize(page.getSize());
        pageVO.setRecords(page.getRecords());
        pageVO.setTotal(page.getTotal());
        return pageVO;
    }

    public static <V1, V2> PageResult<V2> exchange(PageResult<V1> source,
                                                   Function<? super V1, ? extends V2> mapper) {
        PageResult<V2> target = new PageResult<>();
        target.setPages(source.getPages());
        target.setCurrent(source.getCurrent());
        target.setSize(source.getSize());
        target.setTotal(source.getTotal());
        target.setRecords(source.records.stream().map(mapper).collect(Collectors.toList()));
        return target;
    }


}
